package com.dayu.gulimall.product.exception;

import com.dayu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @USER: dayu
 * @EMAIL: dayu007@foxmail.com
 * @DATE: 2020/5/13 17:30
 * @DESCRIPTION:
 */
@Slf4j
@RestControllerAdvice(basePackages={"com.dayu.gulimall.product.controller"})
public class GulimallExceptionAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerException(MethodArgumentNotValidException e){
        System.out.println("==============================");
        log.error("数据校验出现了问题 ： {}，异常类：{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> resultMap=new HashMap<>();
        bindingResult.getFieldErrors().forEach(x->{
            resultMap.put(x.getField(),x.getDefaultMessage());
        });
        return R.error(400,"数据校验出现了问题").put("data",resultMap);
    }
    @ExceptionHandler(value = Throwable.class)
    public R handlerException2(Throwable e){
        log.error("请求异常",e);
        return R.error(400,"请求异常").put("data",e.getMessage());
    }
}
